const { executeQuery, pool } = require('../config/dbConfig');
const wsServer = require('../utils/websocket');

// 添加标签处理工具函数
const processTagsString = (tags) => {
  if (!tags) return '';
  
  // 如果是数组，转换为字符串
  if (Array.isArray(tags)) {
    return tags.filter(tag => tag).join(' ');
  }
  
  // 如果是字符串，按空格分割，过滤空值后重新组合
  return tags.split(/\s+/).filter(tag => tag).join(' ');
};

class BookService {
  // 获取书籍列表
  async getBookList() {
    const sql = `
      SELECT 
        p.*,
        u.nickname,
        u.avatar_data,
        (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
        (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comment_count,
        (SELECT AVG(score) FROM ratings WHERE post_id = p.id) as rating
      FROM posts p
      LEFT JOIN users u ON p.user_id = u.id
      ORDER BY p.created_at DESC
    `;
    
    const books = await executeQuery(sql);
    
    // 处理每本书的图片数据
    return books.map(book => {
      try {
        // 解析图片数组
        if (book.images) {
          book.images = typeof book.images === 'string' ? 
            JSON.parse(book.images) : 
            book.images;
        } else {
          book.images = [];
        }
      } catch (e) {
        console.error('解析图片数据失败:', e);
        book.images = [];
      }
      return book;
    });
  }

  // 创建书籍
  async createBook(bookData) {
    try {
      const {
        user_id,
        title,
        author,
        thoughts,
        tags,
        images,
        reading_url
      } = bookData;
  
      // 处理标签
      const processedTags = processTagsString(tags);
  
      // 插入基本信息
      const result = await executeQuery(
        `INSERT INTO posts (user_id, title, author, thoughts, tags, status, images, reading_url)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          user_id, 
          title, 
          author, 
          thoughts, 
          processedTags, 
          1, 
          JSON.stringify(images), 
          reading_url
        ]
      );
  
      // 获取用户昵称
      const [userInfo] = await executeQuery('SELECT nickname FROM users WHERE id = ?', [user_id]);

      // 广播新书籍发布
      const wsServer = require('../utils/websocket');
      wsServer.broadcastNewBook({
        id: result.insertId,
        title,
        author,
        thoughts,
        tags: processedTags.split(/\s+/),
        images: typeof images === 'string' ? JSON.parse(images) : images,
        reading_url,
        nickname: userInfo.nickname,
        createTime: new Date().toISOString()
      });
  
      return {
        id: result.insertId,
        ...bookData,
        tags: processedTags.split(/\s+/)
      };
    } catch (error) {
      throw error;
    }
  }

  // 获取用户的书籍
  async getUserBooks(userId) {
    const books = await executeQuery(
      `SELECT p.*, u.nickname as author_name,
       (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as likes_count,
       (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comments_count,
       (SELECT AVG(score) FROM ratings WHERE post_id = p.id) as avg_rating
       FROM posts p
       LEFT JOIN users u ON p.user_id = u.id
       WHERE p.user_id = ?
       ORDER BY p.created_at DESC`,
      [userId]
    );

    return books;
  }

  // 获取用户喜欢的书籍
  async getLikedBooks(userId) {
    const books = await executeQuery(
      `SELECT 
        p.id,
        p.title,
        p.author,
        p.thoughts,
        p.tags,
        p.images,
        p.like_count,
        p.rating,
        u.username,
        p.created_at
       FROM likes l
       JOIN posts p ON l.post_id = p.id
       LEFT JOIN users u ON p.user_id = u.id
       WHERE l.user_id = ? AND p.status = 1
       ORDER BY l.created_at DESC`,
      [userId]
    );
    return books;
  }

  // 获取单本书籍详情
  async getBookById(id, userId = null) {
    let sql = `
      SELECT 
        b.*,
        u.nickname,
        u.avatar_data,
        (SELECT COUNT(*) FROM likes WHERE post_id = b.id) as like_count,
        (SELECT COUNT(*) FROM comments WHERE post_id = b.id) as comment_count,
        (SELECT AVG(score) FROM ratings WHERE post_id = b.id) as rating,
        (SELECT COUNT(*) FROM ratings WHERE post_id = b.id) as rating_count,
        (SELECT score FROM ratings WHERE post_id = b.id AND user_id = ?) as user_rating,
        (SELECT 1 FROM likes WHERE post_id = b.id AND user_id = ? LIMIT 1) as is_liked
      FROM posts b
      LEFT JOIN users u ON b.user_id = u.id
      WHERE b.id = ?
    `;

    const params = [userId || null, userId || null, id];
    const [book] = await executeQuery(sql, params);

    if (book) {
      // 确保 is_liked 是布尔值
      book.is_liked = Boolean(book.is_liked);
    }

    // 处理图片数据
    try {
      book.images = book.images ? JSON.parse(book.images) : [];
    } catch (e) {
      console.error('解析图片数据失败:', e);
      book.images = [];
    }

    // 确保数值类型正确
    book.like_count = parseInt(book.like_count || 0);
    book.rating_count = parseInt(book.rating_count || 0);
    book.rating = parseFloat(book.rating || 0);
    book.user_rating = parseInt(book.user_rating || 0);

    return book;
  }

  // 更新书籍
  async updateBook(id, userId, bookData) {
    // 检查书籍是否存在且属于该用户
    const book = await executeQuery(
      'SELECT user_id FROM posts WHERE id = ?',
      [id]
    );

    if (!book || book[0].user_id !== userId) {
      throw new Error('无权更新此书籍');
    }

    const updateFields = [];
    const updateValues = [];

    if (bookData.title) {
      updateFields.push('title = ?');
      updateValues.push(bookData.title);
    }
    if (bookData.author) {
      updateFields.push('author = ?');
      updateValues.push(bookData.author);
    }
    if (bookData.thoughts) {
      updateFields.push('thoughts = ?');
      updateValues.push(bookData.thoughts);
    }
    if (bookData.tags) {
      updateFields.push('tags = ?');
      updateValues.push(bookData.tags);
    }
    // if (bookData.cover_image) {
    //   updateFields.push('cover_image = ?');
    //   updateValues.push(bookData.cover_image);
    // }
    if (bookData.images) {
      updateFields.push('images = ?');
      updateValues.push(bookData.images);
    }
    if (bookData.reading_url) {
      updateFields.push('reading_url = ?');
      updateValues.push(bookData.reading_url);
    }

    if (updateFields.length === 0) {
      throw new Error('没有要更新的字段');
    }

    updateValues.push(id);

    await executeQuery(
      `UPDATE posts SET ${updateFields.join(', ')} WHERE id = ?`,
      updateValues
    );

    // 获取更新后的书籍数据
    const updatedBook = await this.getBookById(id);
    
    // 获取用户昵称
    const [userInfo] = await executeQuery('SELECT nickname FROM users WHERE id = ?', [userId]);

    // 广播书籍更新
    wsServer.broadcastBookUpdate({
      id: parseInt(id),
      title: updatedBook.title,
      author: updatedBook.author,
      thoughts: updatedBook.thoughts,
      tags: updatedBook.tags ? updatedBook.tags.split(/\s+/).filter(tag => tag) : [],
      images: typeof updatedBook.images === 'string' ? JSON.parse(updatedBook.images) : updatedBook.images,
      reading_url: updatedBook.reading_url,
      nickname: userInfo.nickname,
      status: updatedBook.status,
      createTime: updatedBook.created_at
    });

    return true;
  }

  // 删除书籍
  async deleteBook(bookId, userId = null) {
    try {
      if (userId) {
        // 检查用户权限
        const book = await this.getBookById(bookId);
        if (book.user_id !== userId) {
          throw new Error('无权删除该书籍');
        }
        await executeQuery(
          'DELETE FROM posts WHERE id = ? AND user_id = ?',
          [bookId, userId]
        );
      } else {
        // 直接删除
        await executeQuery(
          'DELETE FROM posts WHERE id = ?',
          [bookId]
        );
      }

      // 广播删除状态
      wsServer.broadcastBookStatus(bookId, 0, true);
    } catch (error) {
      throw error;
    }
  }

  // 获取评论列表
  async getComments(bookId, userId = null) {
    const sql = `
      SELECT 
        c.*,
        u.nickname as user_name,
        u.avatar_data,
        (SELECT COUNT(*) FROM comment_likes WHERE comment_id = c.id) as like_count,
        ${userId ? '(SELECT COUNT(*) > 0 FROM comment_likes WHERE comment_id = c.id AND user_id = ?) as is_liked' : 'FALSE as is_liked'}
      FROM comments c
      LEFT JOIN users u ON c.user_id = u.id
      WHERE c.post_id = ?
      ORDER BY c.created_at DESC
    `;

    const params = userId ? [userId, bookId] : [bookId];
    const comments = await executeQuery(sql, params);

    return comments;
  }

  // 添加评论
  async addComment(bookId, userId, content) {
    const result = await executeQuery(
      'INSERT INTO comments (post_id, user_id, content) VALUES (?, ?, ?)',
      [bookId, userId, content]
    );

    return result.insertId;
  }

  // 点赞书籍
  async likeBook(bookId, userId) {
    // 先检查是否已点赞
    const [like] = await executeQuery(
      'SELECT id FROM likes WHERE post_id = ? AND user_id = ?',
      [bookId, userId]
    )
    
    if (!like) {
      // 如果没有点赞记录，才插入
      await executeQuery(
        'INSERT INTO likes (post_id, user_id) VALUES (?, ?)',
        [bookId, userId]
      )
    }
    return { code: 200 }
  }

  // 取消点赞
  async unlikeBook(bookId, userId) {
    await executeQuery(
      'DELETE FROM likes WHERE post_id = ? AND user_id = ?',
      [bookId, userId]
    )
    return { code: 200 }
  }

  // 评分书籍
  async rateBook(bookId, userId, score) {
    const ratings = await executeQuery(
      'SELECT id FROM ratings WHERE post_id = ? AND user_id = ?',
      [bookId, userId]
    );

    if (ratings.length > 0) {
      await executeQuery(
        'UPDATE ratings SET score = ? WHERE post_id = ? AND user_id = ?',
        [score, bookId, userId]
      );
    } else {
      await executeQuery(
        'INSERT INTO ratings (post_id, user_id, score) VALUES (?, ?, ?)',
        [bookId, userId, score]
      );
    }

    return true;
  }

  // 点赞评论
  async likeComment(bookId, commentId, userId) {
    // 先检查是否已点赞
    const [like] = await executeQuery(
      'SELECT id FROM comment_likes WHERE comment_id = ? AND user_id = ?',
      [commentId, userId]
    )
    
    if (!like) {
      // 如果没有点赞记录，才插入
      await executeQuery(
        `INSERT INTO comment_likes (comment_id, user_id) VALUES (?, ?)`,
        [commentId, userId]
      )
    }
    return { code: 200 }
  }

  // 取消点赞评论
  async unlikeComment(bookId, commentId, userId) {
    await executeQuery(
      `DELETE FROM comment_likes WHERE comment_id = ? AND user_id = ?`,
      [commentId, userId]
    )
    return { code: 200 }
  }

  // 上架书籍
  async publishBook(id) {
    const result = await executeQuery(
      'UPDATE posts SET status = 1 WHERE id = ?',
      [id]
    );

    if (result.affectedRows > 0) {
      wsServer.broadcastBookStatus(id, 1);
    }

    return result.affectedRows > 0;
  }

  // 下架书籍
  async unpublishBook(id) {
    const result = await executeQuery(
      'UPDATE posts SET status = 0 WHERE id = ?',
      [id]
    );

    if (result.affectedRows > 0) {
      wsServer.broadcastBookStatus(id, 0);
    }

    return result.affectedRows > 0;
  }

  // 删除评论
  async deleteComment(commentId, userId) {
    // 先检查评论是否存在且属于该用户
    const [comment] = await executeQuery(
      'SELECT id FROM comments WHERE id = ? AND user_id = ?',
      [commentId, userId]
    );

    if (!comment) {
      throw new Error('评论不存在或无权删除');
    }

    // 删除评论
    await executeQuery(
      'DELETE FROM comments WHERE id = ?',
      [commentId]
    );

    return true;
  }
}

module.exports = new BookService(); 